package com.heifeng.cloudshelf.mvp.search.presenter;

import android.content.Context;
import android.graphics.Rect;
import androidx.annotation.Nullable;
import com.google.android.material.bottomsheet.BottomSheetBehavior;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.heifeng.cloudshelf.base.MyApp;
import com.heifeng.cloudshelf.R;
import com.heifeng.cloudshelf.base.BaseResponse;
import com.heifeng.cloudshelf.base.RxPresenter;
import com.heifeng.cloudshelf.constants.HTTPConstants;
import com.heifeng.cloudshelf.dao.MapBean;
import com.heifeng.cloudshelf.dao.SearchDefaultBean;
import com.heifeng.cloudshelf.dao.SearchHomeBean;
import com.heifeng.cloudshelf.helper.MyObserver;
import com.heifeng.cloudshelf.helper.RxUtil;
import com.heifeng.cloudshelf.mvp.model.DetailImageInfo;
import com.heifeng.cloudshelf.mvp.search.adapter.SearchHomeRvAdapter;
import com.heifeng.cloudshelf.mvp.search.contract.SearchHomeActivityContract;
import com.heifeng.cloudshelf.network.NetClient;
import com.heifeng.cloudshelf.utils.DensityUtils;
import com.heifeng.cloudshelf.utils.LocationUtils;
import com.heifeng.cloudshelf.utils.LogUtils;
import com.heifeng.cloudshelf.utils.LoginErrorUtils;
import com.heifeng.cloudshelf.utils.SoftKeyboardUtil;
import com.heifeng.cloudshelf.widget.AppDialog;
import com.heifeng.cloudshelf.widget.BottomDialog;
import com.orhanobut.hawk.Hawk;
import com.yarolegovich.discretescrollview.DiscreteScrollView;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;

/**
 * Created by admin on 2019/9/16.
 */

public class SearchHomeActivityPresenter extends RxPresenter<SearchHomeActivityContract.View> implements SearchHomeActivityContract.Presenter, DiscreteScrollView.ScrollListener<RecyclerView.ViewHolder> {
    private List<List<DetailImageInfo>> allList = new ArrayList<>();

    private List<DetailImageInfo> list = new ArrayList<>();

    private BottomDialog bottomSheet;

    private SearchHomeRvAdapter adapter;

    private boolean isSearchView = false;//当前是否搜索结果界面

    private LinearLayoutManager layoutManager;

    EditText et;

    private int pageTotal = 1;
    private int pageIndex = 1;

    @Inject
    public SearchHomeActivityPresenter() {
    }

    @Override
    public void init() {

        initBottomDialog();

        layoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        mView.getRecyclerView().setLayoutManager(layoutManager);

        adapter = new SearchHomeRvAdapter(mContext, R.layout.layout_searchhome_rv_item, list);
        adapter.setHasStableIds(true);
        ((DefaultItemAnimator) mView.getRecyclerView().getItemAnimator()).setSupportsChangeAnimations(false); // 取消动画效果
        mView.getRecyclerView().setAdapter(adapter);

//        initData();
    }

    @Override
    public void setPageIndex(int pageIndex) {
        this.pageIndex = pageIndex;
    }

    @Override
    public boolean isVisBottom(RecyclerView recyclerView) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        //屏幕中最后一个可见子项的position
        int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
        //当前屏幕所看到的子项个数
        int visibleItemCount = layoutManager.getChildCount();
        //当前RecyclerView的所有子项个数
        int totalItemCount = layoutManager.getItemCount();
        //RecyclerView的滑动状态
        int state = recyclerView.getScrollState();

        if (visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 && state == recyclerView.SCROLL_STATE_IDLE) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void nextPage(String address) {
        if (pageIndex + 1 <= pageTotal) {
            pageIndex += 1;
            toSearchCommunityList(address);
        }
    }

    @Override
    public boolean isSearchView() {
        return isSearchView;
    }

    @Override
    public void setIsSearchView(boolean flag) {
        isSearchView = flag;
    }

    @Override
    public void toSearchCommunityList(String address) {
        LogUtils.e("TvSearch toSearchCommunityList searchName:" + address + ",currentCity:" + HTTPConstants.city);
        LogUtils.e("TvSearch toSearchCommunityList pageIndex:" + pageIndex);
        Map<String, Object> map = new HashMap<>();
        map.put("pageNo", pageIndex);
        map.put("pageSize", 15);
        map.put("currentCity", HTTPConstants.city);
//        searchName:null
        if (!TextUtils.isEmpty(address)) {
            map.put("searchName", address);
        }
        NetClient.getInstance().getNetApi().toSearchCommunityList(map)
                .compose(RxUtil.<BaseResponse<SearchHomeBean>>rxSchedulers())
                .subscribe(new MyObserver<BaseResponse<SearchHomeBean>>(mContext) {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseResponse<SearchHomeBean> baseResponse) {
                        if (0 == baseResponse.getCode()) {
                            initData(baseResponse.getresult().getData());
                            if (null != mView) {
                                mView.setListSize(baseResponse.getresult().getPageTotal());
                                mView.showNoDatas(baseResponse.getresult().getPageTotal() <= 0);
                            }
                            pageTotal = baseResponse.getresult().getPageTotal();
                        } else {
                            LoginErrorUtils.loginOut(mContext, baseResponse.getCode(), baseResponse.getmsg());
                            if (null != mView) {
                                if (500015 == baseResponse.getCode()) {
                                    List<SearchDefaultBean> data = new ArrayList<>();
                                    for (int i = 0; i < baseResponse.getresult().getData().size(); i++) {
                                        SearchHomeBean.DataBean dataBean = baseResponse.getresult().getData().get(i);
                                        data.add(new SearchDefaultBean(dataBean.getId(), dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress()));
                                    }
                                    if (pageIndex <= 1) {
                                        if (null != mView) {
                                            list.clear();
                                            adapter.setNewData(list);
                                            mView.noSreachData(data);
                                        }
                                    }
                                } else {
                                    list.clear();
                                    adapter.setNewData(list);
                                    mView.showNoDatas(true);
                                }
                            }
                        }
                    }
                });
    }

    public void initData(List<SearchHomeBean.DataBean> data) {//模拟初始数据
        if (1 == pageIndex) {
            list.clear();
        }
        allList.clear();
        if (null != data && data.size() > 0) {
            int count = 0;

            if (list.size() > 0) {
                DetailImageInfo detailImageInfo = list.get(list.size() - 1);
                if (null == detailImageInfo.getFirstImage()) {
                    SearchHomeBean.DataBean dataBean = data.get(0);
                    DetailImageInfo.ImageInfoBean urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress(), -1, dataBean.getId());
                    detailImageInfo.setFirstImage(urlImage);
                    count = 1;
                }
                if (null == detailImageInfo.getSecondImage() && data.size() > 1) {
                    SearchHomeBean.DataBean dataBean = null;
                    if (null == detailImageInfo.getFirstImage()) {
                        dataBean = data.get(0);
                        count = 1;
                    }else{
                        dataBean = data.get(1);
                        count = 2;
                    }
                    DetailImageInfo.ImageInfoBean urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress(), -1, dataBean.getId());
                    detailImageInfo.setSecondImage(urlImage);
                }
            }

            DetailImageInfo.ImageInfoBean urlImage;
            DetailImageInfo.ImageInfoBean urlImage1;
            while (data.size() > count) {
                urlImage = null;
                urlImage1 = null;
                if (count < data.size()) {
                    SearchHomeBean.DataBean dataBean = data.get(count);
                    urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress(), -1, dataBean.getId());
                    if (count + 1 < data.size()) {
                        dataBean = data.get(count + 1);
                        urlImage1 = new DetailImageInfo.ImageInfoBean(dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress(), -1, dataBean.getId());
                    }
                } else if (data.size() < count && count - 1 < data.size()) {
                    SearchHomeBean.DataBean dataBean = data.get(count);
                    urlImage = new DetailImageInfo.ImageInfoBean(dataBean.getCloudImage(), dataBean.getName(), dataBean.getAddress(), -1, dataBean.getId());
                }

                if (null != urlImage) {
                    DetailImageInfo info = new DetailImageInfo(urlImage, urlImage1);
                    list.add(info);
                }
                count += 2;
            }
            Glide.get(mContext).clearMemory();
            adapter.notifyDataSetChanged();
        }
    }

    public void initSearchData() {//模拟搜索结果数据
//        list.clear();
//        allList.clear();
//
//        DetailImageInfo info1 = new DetailImageInfo("http://pic16.nipic.com/20111006/6239936_092702973000_2.jpg", "http://pic25.nipic.com/20121112/9252150_150552938000_2.jpg");
//        DetailImageInfo info2 = new DetailImageInfo("http://pic26.nipic.com/20121221/9252150_142515375000_2.jpg", "http://pic13.nipic.com/20110409/7119492_114440620000_2.jpg");
//
//        list.add(info1);
//        list.add(info2);
//
//
//        tempList.clear();
//        tempList = splitList(list, 5);
//        for (int i = 0; i < tempList.size(); i++) {
//            allList.add(tempList.get(i));
//        }
//
//        adapter.notifyDataSetChanged();
    }

    @Override
    public void gdLocation() {
        LocationUtils.synchronizedGetRequests(HTTPConstants.MAPURL, new LocationUtils.OnMessageCallBack() {
            @Override
            public void onMessage(String message) {
                Log.e("TAGS", "message:" + message);
                MapBean mapBean = new Gson().fromJson(message, MapBean.class);
                if (!TextUtils.isEmpty(mapBean.getCity())) {
                    Hawk.put(HTTPConstants.CITY_KEY, mapBean.getCity());
                    Hawk.put(HTTPConstants.PERMISSION_KEY, true);
                    HTTPConstants.city = mapBean.getCity();
                    if (null != mView) {
                        mView.getLocationSuccess();
                    }
                } else {
                    Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                    if (null != mView) {
                        mView.locationError();
                    }
                }
            }

            @Override
            public void onError() {
                Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                if (null != mView) {
                    mView.locationError();
                }
            }
        });
    }

    @Override
    public void ShowLocationFaildDialog() {//系统定位失败dialog
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_location_failed), mContext.getResources().getString(R.string.text_location_failed_try_refresh),
                mContext.getResources().getString(R.string.text_refresh), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        gdLocation();
                    }
                }).showDialog();
    }

    @Override
    public void ShowLocationUnableDialog() {//未开启位置权限dialog
        AppDialog.OneButtonDialog(mContext, mContext.getResources().getString(R.string.text_location_unable), mContext.getResources().getString(R.string.text_open_location_first),
                mContext.getResources().getString(R.string.text_i_know), new AppDialog.OneButtonOnClickListener() {
                    @Override
                    public void onBtnClick() {
                        mView.closeActicity();
                    }
                }).showDialog();
    }

    @Override
    public void ShowAllowLocationDialog() {//允许访问位置信息dialog
        AppDialog.AllowLocationDialog(mContext, new AppDialog.DoubleButtonOnEnquireClickListener() {
            @Override
            public void onLeftClick(boolean isEnquire) {
                //不允许
                Log.e("AllowLocation", "isEnquire:" + isEnquire);
                Hawk.put(HTTPConstants.PERMISSION_KEY, false);
                if (isEnquire) {
                    ShowLocationUnableDialog();
                } else {
                    //返回主页
                    if (null != mView) {
                        mView.closeActicity();
                    }
                }
            }

            @Override
            public void onRightClick(boolean isEnquire) {
                gdLocation();
            }
        }).showDialog();
    }

    /**
     * @param list
     * @param len
     * @return 按指定大小，分隔集合，将集合按规定个数分为n个部分
     */
    public static List<List<DetailImageInfo>> splitList(List<DetailImageInfo> list, int len) {
        if (list == null || list.size() == 0 || len < 1) {
            return new ArrayList<>();
        }
        List<List<DetailImageInfo>> result = new ArrayList<List<DetailImageInfo>>();
        int size = list.size();
        int count = (size + len - 1) / len;
        for (int i = 0; i < count; i++) {
            List<DetailImageInfo> subList = new ArrayList<>();
            subList.addAll(list.subList(i * len, ((i + 1) * len > size ? size : len * (i + 1))));
            result.add(subList);
        }
        return result;
    }

    @Override
    public void onScroll(float scrollPosition, int currentPosition, int newPosition, @Nullable RecyclerView.ViewHolder currentHolder, @Nullable RecyclerView.ViewHolder newCurrent) {

    }

    private void initBottomDialog() {
        bottomSheet = new BottomDialog(mContext);

        View view = LayoutInflater.from(mContext).inflate(R.layout.layout_search_dialog, null, false);

        bottomSheet.setCancelable(false);
        bottomSheet.setCanceledOnTouchOutside(false);

        bottomSheet.setContentView(view);

        bottomSheet.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(R.color.bg_80000000);

        TextView tvSearch = (TextView) view.findViewById(R.id.tv_search);
        TextView tvCancel = (TextView) view.findViewById(R.id.tv_cancel);
        final EditText etSearch = (EditText) view.findViewById(R.id.et_search);
        LinearLayout lView = (LinearLayout) view.findViewById(R.id.l_main);
        LinearLayout layout = (LinearLayout) view.findViewById(R.id.l_container);

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, (int) (MyApp.SCREEN_WIDTH * 0.4));
        layoutParams.setMargins(0, DensityUtils.dp2px(mContext, 40), 0, DensityUtils.dp2px(mContext, 40));
        lView.post(() -> {  //contentView是自定义的显示在BottomSheetDialog上的view
            //R.id.design_bottom_sheet基本是固定的,不用担心后面API的更改
            BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet.findViewById(R.id.design_bottom_sheet));
            behavior.setHideable(false);//此处设置表示禁止BottomSheetBehavior的执行
        });

        layout.setLayoutParams(layoutParams);

        et = etSearch;

        tvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view1) {//搜索
                SoftKeyboardUtil.hideKeyboard(view);
                if (null != mView) {

                    mView.setTvSearchText(etSearch.getText().toString().trim());
                    mView.getIvSearch().setVisibility(View.GONE);
                    isSearchView = true;
                    initSearchData();
                    bottomSheet.dismiss();
                }
            }
        });

        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {//取消
                SoftKeyboardUtil.hideKeyboard(view);

                bottomSheet.dismiss();
            }
        });

        etSearch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            private int statusBarHeight;

            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                // 使用最外层布局填充，进行测算计算
                lView.getWindowVisibleDisplayFrame(r);
                int screenHeight = MyApp.SCREEN_WIDTH;
                int heightDiff = screenHeight - (r.bottom - r.top);
                if (heightDiff > 100) {
                    // 如果超过100个像素，它可能是一个键盘。获取状态栏的高度
                    statusBarHeight = 0;
                }
                try {
                    Class<?> c = Class.forName("com.android.internal.R$dimen");
                    Object obj = c.newInstance();
                    Field field = c.getField("status_bar_height");
                    int x = Integer.parseInt(field.get(obj).toString());
                    statusBarHeight = mContext.getResources().getDimensionPixelSize(x);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // 软键盘的高度
                int realKeyboardHeight = heightDiff - statusBarHeight;

                if (realKeyboardHeight > 400) {

                } else if (realKeyboardHeight < 400) {

                }
            }
        });

    }


    /**
     * 获取虚拟按键的高度
     *
     * @return
     */
    public int getVirtualBarHeigh() {
        int vh = 0;
        WindowManager windowManager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
        Display display = windowManager.getDefaultDisplay();
        DisplayMetrics dm = new DisplayMetrics();
        try {
            @SuppressWarnings("rawtypes")
            Class c = Class.forName("android.view.Display");
            @SuppressWarnings("unchecked")
            Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
            method.invoke(display, dm);
            vh = dm.heightPixels - windowManager.getDefaultDisplay().getHeight();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return vh;
    }

    public void showSearchDialog() {
        bottomSheet.show();
        SoftKeyboardUtil.showInput(mContext, et);
    }
}
